<?php

namespace app\admins\controller;

use app\admins\model\Config;

class Setting extends Base
{
    // Curd复用
    use Curd;

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->model = $this->setting;
        $this->config = new Config();
        $this->map = [['id', '>', 1]];
        $this->sort = ['id' => 'desc'];
        $this->is_page = true;
        $this->rule = [
            'names|字段名' => 'require|alphaDash|token|unique:setting'
        ];

        $is_config = $this->admin_menu->where([
            ['controller', '=', 'Config'],
            ['action', '=', 'index'],
            ['id', 'in', $this->auth['rights']],
            ['status', '=', 0]
        ])->find();
        $this->app->view->assign('is_config', $is_config);
    }

    // 编辑
    public function edit()
    {
        $param = $this->param;
        $row = $this->model->where('id', $param['id'])->find();
        empty($row) && $this->errMsg(1, '数据不存在');
        // 表单字段
        $fields = $this->config->where([
            ['sid', '=', $this->param['id']],
            ['status', '=', 0]
        ])->order([
            'ord' => 'desc',
            'id' => 'asc'
        ])->select()->toArray();
        $fields = array_map(function ($item) {
            $value = json_decode($item['value'], true);
            $options = json_decode($item['options'], true);
            if ($this->is_serialized($item['value'])) {
                $item['value'] = unserialize($item['value']);
            } else if (!is_null($value)) {
                $item['value'] = $value;
            }
            if ($this->is_serialized($item['options'])) {
                $item['options'] = unserialize($item['options']);
            } else if (!is_null($options)) {
                $item['options'] = $options;
            }
            return $item;
        }, $fields);
        // 默认值
        $default = $row['values'];
        $defaults = json_decode($row['values'], true);
        if ($this->is_serialized($row['values'])) {
            $default = unserialize($row['values']);
        } else if (!is_null($defaults)) {
            $default = $defaults;
        }
        // 渲染
        $this->app->view->assign('fields', $fields);
        $this->app->view->assign('default', $default);
        $this->app->view->assign('row', $row->getData());
        return $this->app->view->fetch();
    }

    // 保存编辑
    public function save_edit()
    {
        $param = $this->param;
        $row = $this->model->where('id', $param['id'])->find();
        empty($row) && $this->errMsg(1, '数据不存在');
        // 验证 token
        !$this->request->checkToken() && $this->errMsg(1, '令牌数据无效');
        $fields = $this->config->where([
            ['sid', '=', $this->param['id']],
            ['status', '=', 0]
        ])->order([
            'ord' => 'desc',
            'id' => 'asc'
        ])->select()->toArray();
        $allow = array_column($fields, 'name');
        $attachments = false;
        if ($allow) {
            if ($this->is_serialized($row['values'])) {
                $values = array_intersect_key($param, array_flip($allow));
                $attachments = $values;
                $values = serialize($values);
            } else {
                $values = array_intersect_key($param, array_flip($allow));
                $attachments = $values;
                $values = json_encode($values);
            }
        } else {
            $values = $param['values'];
            $attachments = $values;
        }
        // 数据中是否有附件
        $attachs = [];
        if ($attachments) {
            if (is_array($attachments)) {
                foreach($attachments as $k => $attachment) {
                    if (preg_match('/\/storage\/.+?\./i', $attachment)) {
                        $attachs[] = $attachment;
                    }
                }
            } else {
                if (preg_match('/\/storage\/.+?\./i', $attachments)) {
                    $attachs[] = $attachments;
                }
            }
        }
        $attachs = array_unique($attachs);
        $datas = ['names' => $param['names'], 'values' => $values];
        // 操作
        try {
            $save = $row ? $row->save($datas) : $this->model->save($datas);
        } catch (\Exception $e) {
            $this->errMsg(1, $e->getMessage());
        }
        // 更新文件管理
        $save && $attachs && $this->app->db->table('files')->whereIn('path', $attachs)->update(['status' => 0]);
        $save ? $this->errMsg(0, '保存成功') : $this->errMsg(1, '保存失败');
    }

    // 基础设置
    public function basesetting()
    {
        $basics = [
            ['label' => '站点Logo', 'name' => 'logo', 'type' => 'upload'],
            ['label' => '站点名称', 'name' => 'siteName', 'lay-verify' => 'required', 'value' => 'thinkphp测试'],
            ['label' => '站点域名', 'name' => 'siteUrl', 'value' => '', 'placeholder' => '默认相对路径', 'desc' => '如 https://www.baidu.com'],
            ['label' => 'SEO标题', 'name' => 'title', 'lay-verify' => 'required', 'value' => 'thinkphp title'],
            ['label' => 'SEO描述', 'name' => 'description', 'type' => 'textarea', 'lay-verify' => 'required', 'value' => 'thinkphp description'],
            // ['label' => '底部小导航', 'name' => 'minNav', 'type' => 'textarea', 'value' => ''],
            ['label' => '版权信息', 'name' => 'copyright', 'type' => 'textarea', 'value' => '© ' . date('Y') . ' Company, Inc.'],
            ['label' => '上传类型', 'name' => 'exts', 'value' => 'gif|jpg|jpeg|png|zip', 'desc' => '允许上传的文件类型'],
            ['label' => '限制大小', 'name' => 'size', 'type' => 'number', 'lay-verify' => 'required|number', 'value' => '10240', 'desc' => '单位 KB 默认最大 10MB'],
            ['label' => '蜘蛛不索引', 'name' => 'robots', 'type' => 'switch'],
            ['label' => '单点登录', 'name' => 'oneLogin', 'type' => 'switch'],
            ['label' => 'ICP备案号', 'name' => 'icp'],
        ];

        $advanced = [
            ['label' => '轮播图1', 'name' => 'slide1', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url1'],
            ['label' => '轮播图2', 'name' => 'slide2', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url2'],
            ['label' => '轮播图3', 'name' => 'slide3', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url3'],
            ['label' => '轮播图4', 'name' => 'slide4', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url4'],
            ['label' => '轮播图5', 'name' => 'slide5', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url5'],
        ];

        $other = [
            ['label' => '热门文章', 'name' => 'hots', 'type' => 'number', 'value' => 5, 'desc' => '条显示'],
            ['label' => '点击排行', 'name' => 'views', 'type' => 'number', 'value' => 5, 'desc' => '条显示'],
            ['label' => '最近更新', 'name' => 'news', 'type' => 'number', 'value' => 5, 'desc' => '条显示'],
            ['label' => '相关文章', 'name' => 'related', 'type' => 'number', 'value' => 6, 'desc' => '条显示'],
            ['label' => '图片分类ID', 'name' => 'grid', 'type' => 'text', 'value' => 0, 'desc' => '多个分类半角 , 隔开'],
            ['label' => '图片分页', 'name' => 'gridNum', 'type' => 'number', 'value' => 24, 'desc' => '条显示'],
            // ['label' => '评论嵌套', 'name' => 'commentsLevel', 'type' => 'number', 'value' => 5, 'desc' => '层最多'],
            ['label' => '内容声明', 'name' => 'statement', 'type' => 'textarea', 'rows' => 3, 'value' => '<p>本文链接：{url}</p>
            <p>转载声明：本站文章若无特别说明，皆为原创，转载请注明来源！</p>', 'desc' => '{title} 文章标题 {url} 文章地址'],
        ];

        $row = $this->model->where('names', 'base_setting')->find();
        if ($this->request->isAjax()) {
            $param = $this->param;
            !$this->request->checkToken() && $this->errMsg(1, '令牌数据无效');
            $allow = array_column(array_merge($basics, $advanced, $other), 'name');
            $values = array_intersect_key($param, array_flip($allow));
            // json数据中是否有附件
            $attachs = [];
            foreach($values as $k => $attachment) {
                if (preg_match('/\/storage\/.+?\./i', $attachment)) {
                    $attachs[] = $attachment;
                }
            }
            $values = json_encode($values);
            $datas = ['names' => 'base_setting', 'values' => $values];
            try {
                $save = $row ? $row->save($datas) : $this->model->save($datas);
            } catch (\Exception $e) {
                $this->errMsg(1, $e->getMessage());
            }
            // 更新文件管理
            $save && $attachs && $this->app->db->table('files')->whereIn('path', $attachs)->update(['status' => 0]);
            $save ? $this->errMsg(0, '保存成功') : $this->errMsg(1, '保存失败');
        } else {
            $default = [];
            $row && $default = json_decode($row['values'], true);
            $this->app->view->assign('default', $default);
            $this->app->view->assign('fields', compact('basics', 'advanced', 'other'));
            return $this->app->view->fetch();
        }
    }

    // 返回数据
    private function datas($datas)
    {
        $datas = $datas->map(function ($item) {
            // $item['status'] = $item['status'] ? '<span style="color:#c2c2c2">禁用</span>' : '<span style="color:#5FB878">启用</span>';
            return $item;
        });
        return $datas;
    }
}
